<template>
    <ModalCom v-bind="$attrs" width="520px" @open="modalOpen" :inner-loading="innerLoading" :ok-async="okAsync">
      <Form ref="formFieldsRef" :list="state.controlList" :fields="state.fields"></Form>
    </ModalCom>
</template>

<script setup>
import { reactive, ref } from "vue"
// 跨级组件
import ModalCom from "@/components/modal/index.vue"
import Form from "@/components/form/index.vue"
// 校验函数
import { validateRequired } from "@/utils/index"
//message
import { message } from "ant-design-vue"
// api
import { roleListAll } from "@/api/role"
import { userSetRole, userGetRole } from "@/api/user"
// props
const props = defineProps({
  row: {
    type: Object,
    default: () => ({})
  }
})
// formFieldsRef
const formFieldsRef = ref(null)
const state = reactive({
  controlList: [
    { 
      label: "选择角色", 
      field: "roleId", 
      control: "select", 
      maxlength: 20,
      name: "role_name",
      id: "role_id",
      options: [],
      rules: [validateRequired("请选择角色")]
    },
  ],
  fields: {
    roleId: "",
  }
})

const okAsync = () => {
  return new Promise((resolve, reject) => { // then，catch
    formFieldsRef.value.validataForm().then(() => {
      userSetRole({
        id: props.row.member_id,
        role_ids: state.fields.roleId
      }).then(res => {
        message.success(res?.msg)
        resolve()
      }).catch(() => {
        reject()
      })
    }).catch(() => {
      reject()
    })
    
    
  })
}

const innerLoading = () => {
  return new Promise((resolve, reject) => { // then，catch
    userGetRole({id: props.row.member_id}).then(res => {
      state.fields.roleId = res.content
    })
    roleListAll().then(res => {
      state.controlList[0].options = res?.content || []
      resolve()
    })
  })
}
const modalOpen = () => {
  state.fields.name = props.row.bookname
}
</script>